<template>
  <div id="body" ref="body">
    <el-button class="colCardBox" style="" icon="el-icon-d-arrow-right" @click="collapseCardBox" />
    <!-- 监控视频窗口 -->
    <el-card v-show="motitorShow" class="card-monitor">
      <div slot="header" class="clearfix">
        <el-button style="float: right; margin-top: -10px;" type="text" @click="closeMonitorWindow">
          {{ $t('operating.close') }}
        </el-button>
      </div>
      <!-- <v-liveplayer class="monitor-preview" ref="mymonitor" h5id="2"
                    style="width: 400px; height: 225px;"></v-liveplayer> -->
    </el-card>

    <el-card class="card-box">
      <div class="handle-div1">
        <el-button
          style="background-image: linear-gradient(180deg, #1f59ad, #3488de) !important; color: #fff;"
          @click="customStatistics"
        >
          {{ $t('realtime.customStatistics') }}
        </el-button>
        <el-button style="background-color: red; color: #fff;" @click="customAlarmArea">
          {{ $t('realtime.rapidEvacuation') }}
        </el-button>

      </div>
      <div class="handle-div2">
        <el-select
          v-model="searchValue"
          :placeholder="$t('realtime.searchValue')"
          filterable
          :filter-method="filterDeptObj"
          style="width:155px; left:-12px;"
        >
          <el-option
            v-for="item in deptObjData"
            :key="item.resourceId"
            :label="item.name"
            :value="item.resourceId"
          />
        </el-select>
        <el-button
          icon="el-icon-search"
          circle
          style="background-color:#f1a11e; color: #fff;"
          @click="search()"
        />

        <el-tooltip
          :hide-after="1000"
          effect="dark"
          :content="mapScreen?`${ $t('header.cancelFullScreen')}`:`${ $t('header.fullScreen')}`"
          placement="top"
        >
          <el-button icon="el-icon-rank" circle @click="fullScreen" />
        </el-tooltip>
      </div>

      <div class="handle-div4">
        <el-collapse v-model="activeName" class="collapse1">
          <el-collapse-item :title="$t('realtime.map')" name="zero" style="background-color:#7ba8e2">
            <el-tree
              class="filter-tree"
              :data="mapTreeData"
              :props="this.v_DefaultProps"
              default-expand-all
              :filter-node-method="filterNode"
              :expand-on-click-node="false"
              @node-click="nodeClick"
            >
              <span slot-scope="{node, data}" class="custom-tree-node">
                <span class="el-tree-node__label">{{ node.label }}</span>
                <!--                <span>-->
                <!--                  <el-button type="text" size="mini" @click="()=>detail(node, data)">{{$t('realtime.tunnel.staffDetails')}}</el-button>-->
                <!--                </span>-->
              </span>
            </el-tree>
          </el-collapse-item>
          <el-collapse-item :title="$t('realtime.resourceList')">
            <el-collapse class="collapse2" accordion>
              <el-collapse-item :title="$t('realtime.areaList')" name="first">
                <el-table
                  :data="tableFence"
                  style="width:100%"
                  max-height="300"
                  @select="clickShowFence"
                  @select-all="clickShowCompleteFence"
                >
                  <el-table-column type="selection" width="30" />
                  <el-table-column prop="fenceName" :label="$t('realtime.fenceName')" />
                  <el-table-column
                    prop="fenceType"
                    :label="$t('realtime.fenceType')"
                    :filters="fenceFilterType"
                    :filter-method="resourceTypeFilterHandler"
                  />
                  <el-table-column prop="num" :label="$t('realtime.num')" />
                </el-table>
              </el-collapse-item>
              <el-collapse-item :title="$t('realtime.resourceList')" name="second">
                <el-table
                  ref="resourceList"
                  :data="tableResource"
                  style="width:100%"
                  max-height="300"
                  :row-class-name="resourceTableRowClassName"
                >
                  <el-table-column :label="$t('realtime.showContrail')">
                    <template slot-scope="scope">
                      <el-switch v-model="scope.row.showContrail" @change="handleChangeSwitch(scope.row)" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="name" width="100" :label="$t('realtime.resourceName')" />
                  <el-table-column
                    prop="type"
                    width="60"
                    :label="$t('realtime.resourceType')"
                    :filters="resourceFilterType"
                    :filter-method="resourceTypeFilterHandler"
                  />
                  <el-table-column
                    prop="rateHeart"
                    :width="rateHeartColumnWidth"
                    :label="$t('realtime.resourceHeartRate')"
                  />
                  <el-table-column>
                    <template slot-scope="scope">
                      <el-button size="mini" type="primary" @click="handleFollowing(scope.$index, scope.row)">
                        {{ $t('realtime.track') }}
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-collapse-item>
              <el-collapse-item :title="$t('realtime.cameraList')" name="third">
                <el-table
                  :data="tableCamera"
                  style="width:100%"
                  max-height="300"
                  @select="clickShowCamera"
                  @select-all="clickShowCompleteCamera"
                >
                  <el-table-column type="selection" width="30" />
                  <el-table-column prop="cameraName" :label="$t('realtime.cameraName')" />
                  <el-table-column prop="cameraVendor" :label="$t('realtime.cameraVendor')" />
                  <el-table-column :label="$t('operating.operating')">
                    <template slot-scope="scope">
                      <el-button size="mini" type="primary" @click="handlePreview(scope.$index, scope.row)">
                        {{ $t('realtime.Preview') }}
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-collapse-item>
            </el-collapse>
          </el-collapse-item>

        </el-collapse>
      </div>
    </el-card>

    <div id="mapbox2" :style="{height: mapHeight, width: mapWidth}">
      <!-- 地图容器 -->
      <div id="map" :style="{height: mapHeight, width: mapWidth}" />

      <!-- 弹出气泡 -->
      <div style="display: none" class="popup-info-div">
        <div id="popup-info" class="ol-popup">
          <a id="popup-closer" href="javascript:;" class="ol-popup-closer" :title="$t('realtime.close')" />
          <div id="popup-content" />
        </div>
      </div>
      <!-- 弹出视频窗口 -->
      <div style="display: none;" class="popup-video-div">
        <div id="popup-video" class="ol-popup">
          <a id="popup-video-closer" href="javascript:;" class="ol-popup-closer" :title="$t('realtime.close')" />
          <!-- <iframe id="popup-video-iframe" :src="cameraPlayUrl" scrolling="no" style="width:400px; height:225px;"></iframe> -->
          <!-- <v-liveplayer class="camera-preview" ref="myvideo" h5id="1"
                        style="width: 400px; height: 225px;"></v-liveplayer> -->
        </div>
      </div>

      <div class="positiondiv">
        <span />
      </div>
      <div class="scalediv">
        <span />
      </div>
    </div>

    <!-- 进出门事件展示列表 -->
    <el-table
      class="gateeventtable"
      :data="gateEventTableData"
      max-height="250"
      :row-class-name="gateTableRowClassName"
    >
      <el-table-column prop="event" :label="$t('realtime.event')" width="120" />
      <el-table-column prop="detail" :label="$t('realtime.eventDetail')" width="200" />
      <el-table-column prop="reportTime" :label="$t('realtime.eventTime')" width="200" />
    </el-table>
    <!-- 本图层的统计信息显示模块 -->
    <div class="show5">
      <div class="show_subdiv" style="left: 0px;">
        <span class="span_num">{{ statisticInfo.staff }}</span>
        <div class="pillardiv_staff" />
        <span class="span_title">{{ $t('realtime.staff') }}</span>
      </div>
      <div class="show_subdiv" style="left: 50px;">
        <span class="span_num">{{ statisticInfo.celler }}</span>
        <div class="pillardiv_celler" />
        <span class="span_title">{{ $t('realtime.celler') }}</span>
      </div>
      <div class="show_subdiv" style="left: 100px;">
        <span class="span_num">{{ statisticInfo.car }}</span>
        <div class="pillardiv_car" />
        <span class="span_title">{{ $t('realtime.car') }}</span>
      </div>
      <div class="show_subdiv" style="left: 150px;">
        <span class="span_num">{{ statisticInfo.material }}</span>
        <div class="pillardiv_material" />
        <span class="span_title">{{ $t('realtime.material') }}</span>
      </div>
      <div class="show_subdiv" style="left: 200px;">
        <span class="span_num">{{ statisticInfo.machine }}</span>
        <div class="pillardiv_machine" />
        <span class="span_title">{{ $t('realtime.machine') }}</span>
      </div>
      <div class="show_subdiv" style="left: 250px;">
        <span class="span_num">{{ statisticInfo.boat }}</span>
        <div class="pillardiv_boat" />
        <span class="span_title">{{ $t('realtime.boat') }}</span>
      </div>
      <div class="show_subdiv" style="left: 300px;">
        <span class="span_num">{{ statisticInfo.unknow }}</span>
        <div class="pillardiv_unknow" />
        <span class="span_title">{{ $t('realtime.unknow') }}</span>
      </div>
    </div>

    <el-dialog :title="layerDetailDialogTitle" :visible.sync="showLayerDetail" custom-class="layer_detail_dialog">
      3333
      <el-table :data="layerDetailData" max-height="400">
        <el-table-column type="index" width="50" />
        <el-table-column prop="departmentName" width="100" :label="$t('realtime.deptname')" />
        <el-table-column prop="name" width="100" :label="$t('realtime.resourceName')" />
        <el-table-column prop="workTypeName" width="100" :label="$t('realtime.tunnel.workType')" />
        <el-table-column prop="inGateTime" width="200" :label="$t('realtime.tunnel.holeEntryTime')" />
      </el-table>
    </el-dialog>

    <el-dialog
      :title="numTitle"
      :visible.sync="show7"
      @close="fastStatisticsDialog"
    >
      asdfasdfasdf
      <el-table :data="fastStatistics" max-height="500" :row-class-name="resourceTableRowClassName">
        <el-table-column type="index" width="50" />
        <el-table-column prop="name" :label="$t('realtime.resourceName')" />
        <el-table-column prop="tagElectricity" :label="$t('realtime.tagElectricity')" /> <!-- 电量 -->
        <el-table-column prop="deptname" :label="$t('realtime.deptname')" />
        <el-table-column prop="type" :label="$t('realtime.resourceType')" />
        <el-table-column prop="worktypename" :label="$t('realtime.worktypename')" />
        <el-table-column prop="tagId" :label="$t('realtime.tagId')" />
        <el-table-column
          prop="rateHeart"
          :label="$t('realtime.rateHeart')"
          :width="rateHeartColumnWidth"
        />
      </el-table>
    </el-dialog>

  </div>
</template>

<script>

import { Modify, Snap, Select, Translate } from 'ol/interaction.js'
import { Tile as TileLayer, Vector as VectorLayer, Image } from 'ol/layer.js'
import { Circle, LineString, Point, Polygon } from 'ol/geom.js'
import { OSM, Vector, ImageStatic } from 'ol/source.js'
import { GeoJSON } from 'ol/format.js'
import Draw, { createRegularPolygon, createBox } from 'ol/interaction/Draw.js'
import { Fill, Stroke, Style, Text, Icon } from 'ol/style.js'
import Feature from 'ol/Feature.js'
import {
  Load_Map,
  Load_Fence,
  _TransPixel,
  TagStyle,
  _dPR,
  _iMap,
  OverlayLayer,
  FenceLayer,
  FenceSource,
  checkZoom,
  _TransMetric,
  Tooltip,
  TooltipElement,
  Load_Camera,
  CameraLayer,
  CameraSource,
  _PopupVideo,
  _Popup,
  releaseFence,
  setMapCenter,
  releaseOverlay,
  updateOverlayPosition,
  LoadTypeData,
  clearFence,
  _TransMetric_Number,
  sendThis,
  flashAnimate,
  removeMap
  /** **绘制相关****/

  /** **绘制相关****/
} from '@/utils/iMap.js'
import { setTimeout, clearInterval } from 'timers'
import {
  webSockUrl,
  webSockStatisticsUrl,
  cameraServerUrl,
  baseUrl,
  initPicPath,
  webSockMonitorUrl,
  rateHeartShow
} from '@/utils/global'
import bus from '@/utils/bus'
import {
  getLayerFenceList,
  getAllDeptDetail,
  getCurrentLayerDetail,
  getMapTree,
  getMap
} from '@/api/location'

//   import vCamera from '../common/CameraPreview'
import Cookie from 'js-cookie'

export default {

  components: {
    //   'v-liveplayer': vCamera
  },

  data() {
    return {
      colCardBox: false,
      systomID: '0', // 时间戳，用于系统标识

      /** 工具条相关**/
      checkboxGroup: [], // 存储选择的值
      toolCheck: ['统计', '名称', '职工', '访客', '车辆', '物料'],
      activeName: 'zero', // 当前选中的值
      statisticInfo: {
        staff: 0,
        celler: 0,
        car: 0,
        material: 0,
        machine: 0,
        boat: 0,
        unknow: 0
      },
      /** 工具条相关**/

      mapTreeData: [],
      searchValue: '', // 要搜索的内容
      deptObjData: [], // 资源列表
      deptObjDataCopy: [], // 资源列表副本
      searchLock: false,
      /** ***********表格相关************/
      tableFence: [], // 围栏列表数据

      tableCamera: [], // 模拟的摄像头列表信息
      tableResource: [], // 资源列表
      GeoJsonCamera: [], // 存错本层的摄像头信息
      // mulSelCamera: [], //存储选择的摄像头
      cameraPlayUrl: '', // 摄像头浏览页面地址
      /** ***********表格相关************/

      /** ***********显示相关************/
      show1: true, // 树结构是否显示
      show2: false, // 显示地图中显示项控制台
      // show3: false, //下发告警时的围栏列表弹框
      show7: false, // 统计资源的弹框
      show6: true, // 资源列表摄像头预览

      showFence: false, // 显示围栏
      showPosIcon: true, // 以图标的形式显示位置点
      showPosName: true, // 显示位置的名称
      showPosDetailMsg: true, // 显示位置的详细信息
      showStatisticalInfo: true, // 显示统计信息
      warningAssCamera: true, // 告警关联摄像头
      showWarnMsg: false, // 显示告警信息

      showLayerDetail: false, // 显示当前层中的详细人员信息
      layerDetailData: [], // 当前层中详细人员信息
      layerDetailDialogTitle: '', // 显示层详细信息弹出框的名称
      gateEventTableData: [], // 进出门事件通知集合
      /** ***********显示相关************/
      filterText: '', // 输入框的值
      mapHeight: window.innerHeight - 80 + 'px', // 地图区域高度
      mapWidth: window.innerWidth + 'px',
      mapScreen: false, // 地图是否全屏
      //  **************地图相关参数**************  //
      oldGeo: '', // 存储老的链接地址，用于比对点击楼层时，比对是否是同一个链接
      bLockEx: true, // 刷新数据过程锁，防止刷新过程中强制中断刷新
      bLockExEx: false, // 定时清理内存
      TagLayer: null, // 标签图层
      TagSource: null, // 标签资源容器

      LineLayer: null, // 线条图层
      LineSource: null, // 线条容器

      _areaId: -1, // 记录当前显示的层号
      bAgeLock: false, // 判断是否检查老化数据
      oldMapId: '', // 记录老的地图ID，防止频繁点击同一个地图分支
      Geo: '', // 请求实时位置的链接
      delay: 1000, // 定时请求并刷新界面的时间，单位ms
      mapId: 0,
      mapName: '',
      lastUpdateTime: null,
      //  **************地图相关参数**************  //
      websock: null,
      webMonitorSock: null,
      /** ***************************自定义区域相关****************************/
      Box: null, // 矩形
      newFence: null, // 绘制的撤离区域
      bStatistics: false, // 是否点击的为统计按钮
      fastStatistics: [], // 快速统计的统计结果
      numTitle: '',
      /** ***************************自定义区域相关****************************/

      fenceArrayLength: 0, // 围栏列表勾选的围栏数量
      cameraArrayLength: 0, // 摄像头列表勾选的摄像头数量
      myInterval1: null,

      fenceFilterType: [
        { text: this.$t('realtime.fenceFilterType.mainFence'), value: this.$t('realtime.fenceFilterType.mainFence') },
        { text: this.$t('realtime.fenceFilterType.alarm'), value: this.$t('realtime.fenceFilterType.alarm') },
        { text: this.$t('realtime.fenceFilterType.workArea'), value: this.$t('realtime.fenceFilterType.workArea') },
        { text: this.$t('realtime.fenceFilterType.monitor'), value: this.$t('realtime.fenceFilterType.monitor') },
        { text: this.$t('realtime.fenceFilterType.attendance'), value: this.$t('realtime.fenceFilterType.attendance') },
        { text: this.$t('realtime.fenceFilterType.warehouse'), value: this.$t('realtime.fenceFilterType.warehouse') },
        {
          text: this.$t('realtime.fenceFilterType.operatingArea'),
          value: this.$t('realtime.fenceFilterType.operatingArea')
        },
        { text: this.$t('realtime.fenceFilterType.inspection'), value: this.$t('realtime.fenceFilterType.inspection') },
        {
          text: this.$t('realtime.fenceFilterType.unknownType'),
          value: this.$t('realtime.fenceFilterType.unknownType')
        }
      ],

      resourceFilterType: [
        { text: this.$t('realtime.staff'), value: this.$t('realtime.staff') },
        { text: this.$t('realtime.car'), value: this.$t('realtime.car') },
        { text: this.$t('realtime.celler'), value: this.$t('realtime.celler') },
        { text: this.$t('realtime.material'), value: this.$t('realtime.material') },
        { text: this.$t('realtime.machine'), value: this.$t('realtime.machine') },
        { text: this.$t('realtime.boat'), value: this.$t('realtime.boat') },
        { text: this.$t('realtime.unknow'), value: this.$t('realtime.unknow') }
      ],
      motitorShow: false, // 监控画面是否显示
      rateHeartColumnWidth: 100,

      /** *************绘制相关 ***************/
      styles: {
        'linestring': new Style({
          stroke: new Stroke({
            color: 'green',
            width: 1
          }),
          zIndex: 999
        })
      },

      heartBeatInterval: null,
      order: 0,
      waitTimeInterval: null,
      waitTime: 0, // 等待时间(s)
      waitTimeLock: true,
      sosLock: true
    }
  },

  destroyed: function() {
    this.webSocketOnClose()
  },

  // 钩子
  mounted() {
    // 设置心率是否显示
    if (rateHeartShow) {
      this.rateHeartColumnWidth = 100
    } else {
      this.rateHeartColumnWidth = 1
    }

    const self = this
    bus.$on('removenewfence', msg => {
      if (self.mapId === msg) {
        self.removeNewFence()
      } else {
        console.log('要销毁的撤离围栏不在当前层上')
      }
    })

    // 监听SOS告警，用户为标签添加振波特效
    bus.$on('sosflash', sos => {
      // 检查sos中告警所在的层是不是当前显示的层，如果不是则跳过
      // 如果是，过去地图中的告警对象，为告警对象添加一次振波动画
      this.checkSOSInfo(sos)
    })

    this.cameraPlayUrl = ''

    // 动态设置map的高度
    // 首先在DOM渲染数据时，设置map的高度
    this.windowRefresh()
    // 然后监听window的resize事件，在浏览器窗口变化时再设置下map的高度
    window.onresize = function temp() {
      self.windowRefresh()
    }

    this.init()
    this.$store.commit('changeSosFlashLock', true)
  },

  beforeDestroy() {
    if (this.myInterval1 != null) {
      window.clearInterval(this.myInterval1)
    }

    // 关闭websocket连接
    if (this.websock != null) {
      this.websock.close()
      this.websock = null
      console.log('关闭了位置通道')
    }
    if (this.webMonitorSock != null) {
      this.webMonitorSock.close()
      this.webMonitorSock = null
      console.log('关闭了统计通道')
    }

    this.clearHeartBeatIntervalState()
    this.$store.commit('changeSosFlashLock', false)
    removeMap()
    this.mapId = ''
  },
  // 同步测试
  methods: {
    // switch切换时响应
    handleChangeSwitch(row) {
      console.log('showContrail:', row.showContrail, 'name:', row.name)
      if (this.TagSource != null) {
        const obj = this.TagSource.getFeatureById(row.resourceId)
        if (obj != null) {
          obj.set('showContrail', row.showContrail)
          // console.log('showContrail:', obj);
        }
      }
    },

    resourceTableRowClassName(row, rowIndex) {
      if (!rateHeartShow && row.row.rateHeart) {
        row.row.rateHeart = ''
      }
    },

    // 关闭监控窗口
    closeMonitorWindow() {
      this.motitorShow = false
      if (this.webMonitorSock != null) {
        this.webMonitorSock.close()
        this.webMonitorSock = null
      }
      this.$refs.mymonitor.CloseVideo()
    },

    /**
       * 初始化视频监控通道websocket
       */
    initMonitorWebSocket() {
      // 初始化websocket
      this.webMonitorSock = new WebSocket(webSockMonitorUrl)
      this.webMonitorSock.onopen = this.webMonitorSocketOnOpen
      this.webMonitorSock.onmessage = this.webMonitorSocketOnMessage
      this.webMonitorSock.onclose = this.webMonitorSocketOnClose
      this.webMonitorSock.onerror = this.webMonitorSocketOnError
    },

    /**
       * 注册
       */
    webMonitorSocketOnOpen() {
      if (this.webMonitorSock.readyState === 1) {
        // 发送时间戳
        // this.systomID = (new Date().getTime()).toString();
        // let param = JSON.stringify({register: this.systomID});
        // this.webMonitorSocketOnSend(param);
        console.log('视频跟踪通道连接成功')
      }
    },

    /**
       * 数据发送
       */
    webMonitorSocketOnSend(data) {
      this.webMonitorSock.send(data)
    },
    /**
       * 断开连接
       */
    webSocketOnClose(e) {
      console.log('视频跟踪通道断开连接', e)
    },

    webMonitorSocketOnError(err) {
      console.log('视频跟踪通道连接错误')
    },

    /**
       * 数据接收
       */
    webMonitorSocketOnMessage(e) {
      const self = this
      if (undefined != e.data) {
        const jsonData = JSON.parse(e.data)
        if (jsonData.message === 'handshake') {
          console.log('视频监控通道连接成功')
        } else if (jsonData.message === 'camera') {
          const data = jsonData.data
          this.$refs.mymonitor.PlayVideo(data.h5streamProtocol, data.h5streamHost, data.h5streamToken,
            data.h5streamHlsver, data.h5streamSession)
        }
      }
    },
    // 折叠操作区
    collapseCardBox() {
      this.colCardBox = !this.colCardBox

      if (this.colCardBox) {
        $('.card-box').css('right', '-300px')
        $('.colCardBox').css('right', '0px')
        $('.colCardBox i').attr('class', 'el-icon-d-arrow-left')
      } else {
        $('.card-box').css('right', '0px')
        $('.colCardBox').css('right', '236px')
        $('.colCardBox i').attr('class', 'el-icon-d-arrow-right')
      }
    },
    /**
       * 对资源列表中的围栏进行过滤
       */
    fenceTypeFilterHandler(value, row, column) {
      const property = column['property']
      return row[property] === value
    },
    resourceTypeFilterHandler(value, row, column) {
      const property = column['property']
      return row[property] === value
    },
    /**
       * 资源下拉框支持拼音检索
       */
    filterDeptObj(val) {
      this.objValue = val
      const pinyin = require('pinyin')
      let pinyinName
      if (val) {
        this.deptObjData = this.deptObjDataCopy.filter((item) => {
          if (typeof item.name !== 'undefined') {
            // 将每一个名字都转换成拼音
            pinyinName = pinyin(item.name, {
              heteronym: true, // 启用多音字模式
              style: pinyin.STYLE_NORMAL
            })
            let temp = ''
            for (let i = 0; i < pinyinName.length; i++) {
              temp = temp + pinyinName[i][0].substr(0, 1)
            }

            /**
               * 1、直接从原有的名字中做匹配，考虑大小写的问题
               * 2、将汉字转换成拼音做匹配，考虑大小写的问题
               */
            if ((item.name.indexOf(val) != -1) ||
                (item.name.toLowerCase().indexOf(val) != -1) ||
                (item.name.indexOf(val.toLowerCase()) != -1) ||
                (item.name.toLowerCase().indexOf(val.toLowerCase()) != -1) ||
                (temp.indexOf(val) != -1) ||
                (temp.toLowerCase().indexOf(val) != -1) ||
                (temp.indexOf(val.toLowerCase()) != -1) ||
                (temp.toLowerCase().indexOf(val.toLowerCase()) != -1)) {
              return true
            }
          }
          return false
        })
      } else {
        this.deptObjData = this.deptObjDataCopy
      }
    },

    /**
       * 检查是否有标签气泡和摄像头气泡
       */
    inspectOverlay() {
      // 标签气泡
      const res1 = $('.popup-info-div').children('.ol-popup').length
      if (res1 > 0) {

      } else {
        // 添加气泡标签
        $('.popup-info-div').append('<div id="popup-info" class="ol-popup"><a href="javascript:;" id="popup-closer" class="ol-popup-closer" title="关闭"></a><div id="popup-content"></div></div>')
      }

      // 摄像头气泡
      const res2 = $('.popup-video-div').children('.ol-popup').length
      // if (res2 > 0) {

      // } else {
      //   $('.popup-video-div').append('<div id="popup-video" class="ol-popup"><a href="javascript:;" id="popup-video-closer" class="ol-popup-closer" title="关闭"></a><v-liveplayer class="camera-preview" ref="myvideo" h5id="1" style="width: 400px; height: 225px;"></v-liveplayer></div>')
      // }
    },

    /**
       * 清除地图中的摄像头
       */
    clearCamera() {
      if (CameraSource != null) {
        const old = CameraSource.getFeatures()
        let len = old.length
        while (len > 0) {
          len--
          CameraSource.removeFeature(old[len])
          old.splice(len, 1)
        }
      }
    },
    /**
       * 显示当前勾选的围栏
       */
    clickShowFence(sel, row) {
      // console.log(sel, row);
      if (this.fenceArrayLength > sel.length) { // 取消勾选
        const fence = FenceSource.getFeatureById(row.idx)
        if (fence != null) {
          FenceSource.removeFeature(fence)
        }
      } else { // 勾选
        const url = baseUrl + '/fenceInfo/findByIdGeoJson?idx=' + row.idx
        Load_Fence(url)
      }
      this.fenceArrayLength = sel.length
    },

    /**
       * 点击围栏列表全选按钮时响应
       */
    clickShowCompleteFence(sel) {
      console.log(sel)
      if (this.tableFence.length > 0) { // 表格中有数据
        // 不管是否为勾选状态，都将地图中围栏清空
        clearFence()
        this.fenceArrayLength = sel.length
        if (sel.length > 0) { // 当前为勾选状态
          const url = baseUrl + '/fenceInfo/findListByFenceTypeGeoJson?layerId=' + this.mapId
          Load_Fence(url)
        }
      } else {
        this.v_MyMessage(this.$t('realtime.notificationMessage.noFenceData'), 'warning')
      }
    },

    /**
       * 点击摄像头列表全选按钮时响应
       */
    clickShowCompleteCamera(sel) {
      console.log(sel)
      if (this.tableCamera.length > 0) {
        this.clearCamera()
        this.cameraArrayLength = sel.length
        if (sel.length > 0) {
          const url = baseUrl + '/cameraConfig/findCameraGeoJson?layerId=' + this.mapId
          Load_Camera(url)
        }
      } else {
        this.v_MyMessage(this.$t('realtime.notificationMessage.noCameraData'), 'warning')
      }
    },

    /**
       * 显示当前勾选的摄像头
       */
    clickShowCamera(sel, row) {
      // console.log(sel, row);
      if (this.cameraArrayLength > sel.length) { // 取消勾选
        const camera = CameraSource.getFeatureById(row.idx)
        if (camera != null) {
          CameraSource.removeFeature(camera)
        }
      } else { // 勾选
        const url = baseUrl + '/cameraConfig/findByIdCameraGeoJson?idx=' + row.idx
        Load_Camera(url)
      }
      this.cameraArrayLength = sel.length
    },

    /**
       * 查看人员详情
       */
    detail(node, data) {
      // console.log(node, data)
      // 检查有没有在线人员，如果没有，只做提示，不做弹出
      const index = data.label.indexOf('-')
      let temp = data.label.slice(index + 3)
      // console.log('截取的字符串:', temp)
      if (parseInt(temp) > 0) {
        // 拼接弹框标题
        temp = data.label.slice(0, index)
        this.layerDetailDialogTitle = temp + '---人员详情'
        getCurrentLayerDetail(data.id).then(res => {
          const RES = this.responseUse(res)
          // console.log('获取到的详细信息：', RES)
          this.layerDetailData = RES
          this.showLayerDetail = true
        })
      } else {
        this.v_MyMessage(this.$t('realtime.tunnel.noStaffDetails'), 'info')
      }
    },

    gateTableRowClassName(row) {
      if (row.row.event === 'GATEOUT') {
        row.row.event = this.$t('realtime.tunnel.goingOut')
      } else if (row.row.event === 'GATE_IN') {
        row.row.event = this.$t('realtime.tunnel.entryEvent')
      }
    },

    // 摄像头列表中的预览按钮响应
    handlePreview: function(index, row) {
      // console.log("输出摄像头信息，没有实际预览", row);
      this.$api.realtimeposition.getSingleCameraGeoJson(row.idx).then(res => {
        const RES = this.responseUse(res)
        const format = new GeoJSON()
        const cameraFeatures = format.readFeatures(RES)
        console.log('解析之后的GeoJson数据：', cameraFeatures)

        cameraFeatures.forEach(function(f) {
          const tempcoord = f.getGeometry().getCoordinates()
          const pos = _TransPixel(tempcoord)
          _PopupVideo(f, pos)
        })
      })
    },

    /**
       * 资源跟踪
       */
    handleFollowing(index, row) {
      console.log(index, row)
      this.searchValue = row.resourceId
      this.searchLock = true

      // 打开视频跟踪窗口,创建连接
      this.motitorShow = true
      if (this.webMonitorSock === null) {
        this.initMonitorWebSocket()
      }
    },

    /** ***************************自定义区域相关****************************/
    fenceDraw_init: function() {
      // 矩形
      if (this.Box === null) {
        this.Box = new Draw({
          source: FenceSource,
          type: 'Circle',
          geometryFunction: createBox()
        })
      }
      _iMap.addInteraction(this.Box)
    },

    fenceDraw_setEvents: function(type) {
      const self = this
      let sketch
      const pointerMoveHandler = function(evt) {
        if (evt.dragging) {
          return
        }
        const Msg = '[' + _TransMetric(evt.coordinate, 4) + ']'
        // Tooltip.setPosition(evt.coordinate);
        // $(TooltipElement)
        //   .html(Msg)
        //   .romoveClass("hidden");
      }
      _iMap.on('pointermove', pointerMoveHandler)
      $(_iMap.getViewport()).on('mouseout', function() {
        $(TooltipElement).addClass('hidden')
      })

      // measureTooltip刷新事件
      let listener
      const listenerCoord = function(sketch) {
        listener = sketch.getGeometry().on('change', function(evt) {
          const geom = evt.target
          let tooltipCoord = sketch.getCenter
          let output
          if (geom instanceof Circle) {
            output = formatCircle(geom)
            tooltipCoord = geom.getCenter()
          }
        })
      }

      this[type].on(
        'drawstart',
        function(evt) {
          sketch = evt.feature
          const tooltipCoord = evt.coordinate
          listenerCoord(sketch, tooltipCoord) // 围栏监听
        },
        this
      )

      // 结束绘制事件侦听
      this[type].on(
        'drawend',
        function(evt) {
          listenerCoord(evt.feature) // 围栏监听
          self.newFence = evt.feature

          // let coors = self.newFence.getGeometry().getCoordinates();
          let coors
          if (self.newFence.getGeometry().getType() == 'Circle') {
            coors = self.newFence.getGeometry().getCenter()
            const coorRadiu = self.newFence.getGeometry().getRadius()
            // console.log(coorRadiu);
            coors = '[' + _TransMetric(coors, 4).toString() + ']'
          } else {
            coors = self.newFence.getGeometry().getCoordinates()
            coors = '[' + _TransMetric(coors, 4).toString() + ']'
          }
          // $(TooltipElement).addClass("hidden");//隐藏工具条
          sketch = null

          self.fenceDraw_Destroy()

          if (self.bStatistics) {
            // 统计区域内定位对象数量
            self.customStatisticsMessage()
          } else {
            // 设置自定义撤离信息
            self.customAlarmMessage()
          }
        },
        this
      )

      /**
         * format length output
         * @param {ol.geom.LineString} line
         * @return {string}
         */
      const formatLength = function(line) {
        const length = Math.round(line.getLength() * 100) / 100 / _dPR
        let output
        if (length > 100) {
          output = Math.round((length / 1000) * 100) / 100 + ' ' + 'km'
        } else {
          output = Math.round(length * 100) / 100 + ' ' + 'm'
        }
        return output
      }

      const formatCircle = function(Circle) {
        const area = (2 * Math.PI * Circle.getRadius()) / _dPR / _dPR
        let output
        if (area > 10000) {
          output =
              Math.round((area / 1000000) * 100) / 100 + ' ' + 'km<sup>2</sup>'
        } else {
          output = Math.round(area * 100) / 100 + ' ' + 'm<sup>2</sup>'
        }
        return output
      }
    },

    fenceDraw_getActive: function() {
      return this.activeType ? this[this.activeType].getActive() : false
    },

    fenceDraw_setActive: function(active, type) {
      if (active) {
        this.activeType && this[this.activeType].setActive(false, type)
        this[type].setActive(true, type)
        this.fenceDraw_setEvents(type)
        this.activeType = type
      } else {
        this.activeType && this[this.activeType].setActive(false, type)
        this.activeType = null
      }
    },

    fenceDraw_Destroy: function() {
      if (this.Box != null) {
        this.fenceDraw_setActive(false, 'Box')
        _iMap.removeInteraction(this.Box)
        this.Box = null
        console.log('销毁FenceDraw事件')
      }
    },

    /** ***************************自定义区域相关****************************/
    /**
       * 自定义撤离确认弹框，并支持自定义文字
       */
    customAlarmMessage() {
      const self = this
      this.$prompt(this.$t('realtime.emergencyEvacuation.shortMessage'), this.$t('realtime.emergencyEvacuation.evacuationTitle'), {
        confirmButtonText: this.$t('realtime.emergencyEvacuation.evacuationTitle'),
        cancelButtonText: this.$t('realtime.emergencyEvacuation.cancel'),
        inputPlaceholder: this.$t('realtime.emergencyEvacuation.messageContent'),
        dangerouslyUseHTMLString: true,
        closeOnClickModal: false,
        callback: self.outPromptClose
      }).then(({ value }) => {
        console.log(this.$t('realtime.emergencyEvacuation.evacuationTitle'))
      }).catch(() => {
        console.log('出现了异常')
      })
    },
    outPromptClose(action, instance) {
      if (action === 'cancel') {
        this.removeNewFence()
      } else if (action === 'confirm') {
        // 将信息上传，通过后端对区域内的标签进行撤离信息下发
        const startTime = this.v_GetCurrentDateTime()
        const coors = _TransMetric_Number(this.newFence.getGeometry().getCoordinates(), 4)[0]
        const param = {
          'startTime': startTime,
          'layerId': parseInt(this.mapId),
          'layerName': this.mapName,
          'posGroupArray': coors,
          'des': instance.inputValue
        }
        console.log('param', param)

        this.$api.realtimeposition.oneKeyOut(param).then(res => {
          const RES = this.responseUse(res, true)
          // if(!RES){
          //   self.removeNewFence();
          //   console.log('撤离命令下发成功');
          // }
        })
      }
    },
    removeNewFence() {
      if (FenceSource != null && this.newFence != null) {
        FenceSource.removeFeature(this.newFence)
        this.newFence = null
      }
    },
    /**
       * 快速统计信息弹框
       */
    customStatisticsMessage() {
      // 计算当前这一时刻有多少标签在矩形内
      this.fastStatistics = []
      const resArr = this.TagSource.getFeatures().slice(0)
      const vertkss = this.newFence.getGeometry().getCoordinates()
      let leftVertks
      let rightVertks
      if (vertkss[0].length > 4) {
        leftVertks = _TransMetric(vertkss[0][3], 2)
        rightVertks = _TransMetric(vertkss[0][1], 2)
      }

      let coor, f, type
      for (let index = 0; index < resArr.length; index++) {
        f = resArr[index]
        coor = _TransMetric(f.getGeometry().getCoordinates())

        if (parseFloat(coor[0]) > parseFloat(leftVertks[0]) &&
            parseFloat(coor[0]) < parseFloat(rightVertks[0]) &&
            parseFloat(coor[1]) > parseFloat(leftVertks[1]) &&
            parseFloat(coor[1]) < parseFloat(rightVertks[1])) {
          switch (f.get('type')) {
            case 'staff':
              type = this.$t('realtime.staff')
              break
            case 'car':
              type = this.$t('realtime.car')
              break
            case 'visitor':
              type = this.$t('realtime.celler')
              break
            case 'material':
              type = this.$t('realtime.material')
              break
            case 'machine':
              type = this.$t('realtime.machine')
              break
            case 'boat':
              type = this.$t('realtime.boat')
              break
            default:
              type = this.$t('realtime.unknow')
              break
          }

          const obj = {
            name: f.get('name'),
            tagId: f.get('tag_id'),
            deptname: f.get('deptname'),
            type: type,
            worktypename: f.get('workTypeName'),
            tagElectricity: f.get('tagElectricity'),
            rateHeart: f.get('rateHeart')
          }
          // console.log(f.get('name'));
          this.fastStatistics.push(obj)
        }
      }

      if (this.fastStatistics.length > 0) {
        this.numTitle = this.$t('realtime.common') + this.fastStatistics.length + 'this.$t(\'realtime.aResource\')'
        this.show7 = true
      } else {
        setTimeout(() => {
          this.fastStatisticsDialog()
        }, 1000)
        this.v_MyMessage(this.$t('realtime.notificationMessage.noResourceData'), 'info')
      }
    },
    /**
       * 快速统计
       */
    customStatistics() {
      this.bStatistics = true
      this.customAlarmArea()
    },

    /**
       * 快速统计Dialog关闭时响应
       */
    fastStatisticsDialog() {
      // 1、清除统计数据
      this.fastStatistics.splice(0)
      // 清除围栏
      this.removeNewFence()
      // 清除统计状态
      this.bStatistics = false
    },

    // 自定义撤离区域
    customAlarmArea() {
      // 直接在地图上绘制撤离区域
      // 一次只能画一个一键撤离区域
      // if (null == this.newFence) {
      this.removeNewFence()
      Load_Fence('')
      this.fenceDraw_init()
      this.fenceDraw_setActive(true, 'Box')
      // }
    },

    search() {
      this.$api.realtimeposition.searchResourceInLayer(this.searchValue).then(res => {
        const RES = this.responseUse(res)
        // console.log('资源所在层：', RES.layerId)
        if (RES.layerId != null) {
          // 切换地图，将地图中要搜索的资源居中，并将气泡弹出
          this.mapId = RES.layerId
          this.searchLock = true// 搜索到人员所在的层后，打开锁，对人员进行过滤
          this.changeMap()
        }
      })
    },

    // 显示摄像头
    showCameraInfo() {
      const url = baseUrl + 'cameraConfig/findCameraGeoJson?layerId=' + this.mapId
      Load_Camera(url)
    },

    // 根据输入框中的内容，检索数结构中的内容
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) != -1
    },

    // 全屏显示
    fullScreen() {
      // let element = document.documentElement;
      const element = document.getElementById('body')
      if (this.mapScreen) {
        this.v_MyMessage(this.$t('realtime.notificationMessage.exitFullScreenDisplay'), 'success')
        if (document.exitFullscreen) {
          document.exitFullscreen()
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen()
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen()
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen()
        }
      } else {
        this.v_MyMessage(this.$t('realtime.notificationMessage.fullScreenDisplay'), 'success')
        if (element.requestFullscreen) {
          element.requestFullscreen()
        } else if (element.webkitRequestFullScreen) {
          element.webkitRequestFullScreen()
        } else if (element.mozRequestFullScreen) {
          element.mozRequestFullScreen()
        } else if (element.msRequestFullscreen) {
          // IE11
          element.msRequestFullscreen()
        }
      }
      this.mapScreen = !this.mapScreen
    },

    // 树节点被点击时调用
    nodeClick(draggingNode, dropNode, ev) {
      // 可将地图的ID设置为树结构的ID，通过点击节点，来切换地图
      this.mapId = draggingNode.id

      this.changeMap()
    },

    /**
       * 切换地图
       */
    changeMap() {
      const self = this
      if (self.mapId === '') {
        self.v_MyMessage(this.$t('Notice.mapIDIsEmpty'), 'error')
        return false
      } else {
        if (self.oldMapId !== self.mapId) {
          // releaseOverlay();
          getMap(parseInt(self.mapId)).then(res => {
            const RES = this.responseUse(res)
            if (RES != undefined) {
              // 判断状态码，看是否获取成功
              // 如果获取成功，则将地图ID发送到后端
              if (RES.mapName != undefined) {
                self.mapName = RES.mapName
              }
              Load_Map(
                baseUrl + RES.mapPath,
                RES.mapActualX,
                RES.mapActualY,
                RES.mapPixelX,
                RES.mapPixelY,
                RES.mapPixelX / RES.mapActualX,
                [RES.mapOriginX, RES.mapOriginY]
              )
              self.LoadData(self.mapId, RES.mapOriginX)
              const param = JSON.stringify({ key: self.systomID, layerId: self.mapId })
              self.webSocketOnSend(param)
              // 加载当前层的摄像头(默认不加载)
              // this.showCameraInfo();
              this.inspectOverlay()
            }
          })
          self.getAllFenceInfo()
          self.getAllCameraInfo()
          self.fenceArrayLength = 0

          self.oldMapId = self.mapId
        }
      }
    },

    // 初始化默认地图
    initMap: function() {
      Load_Map(this.$store.state.initPicPath, 67.65, 54.16, 1600, 1280, 1600 / 67.65, [-50, -30])
      sendThis(this)
      LoadTypeData()
    },

    // 往地图中加载数据
    LoadData: function(Geo, OriginX) {
      // 移除标签层信息
      _iMap.removeLayer(this.TagLayer)
      _iMap.removeLayer(this.LineLayer)

      if (this.bLockExEx) {
        this.releaseSource()
        this.bLockExEx = false
      }
      // 切换地图时释放资源
      if (this.oldGeo !== Geo && this.oldGeo !== '') {
        this.oldGeo = Geo
        this.bLockEx = true
        this.releaseSource() // 释放地图中的资源
        this.releaseLineSource()
        releaseFence()
      }
      this.oldGeo = Geo

      if (this.TagSource == null) {
        this.TagSource = new Vector({
          wrapX: false
        })
      }

      if (this.TagLayer == null) {
        this.TagLayer = new VectorLayer({
          minResolution: 0,
          maxResolution: _dPR * 2.4,
          source: this.TagSource,
          zIndex: 10000,
          renderBuffer: 100,
          updateWhileAnimating: true,
          updateWhileInteracting: true,
          style: function(feature, resolution) {
            return TagStyle(feature, resolution, OriginX)
          }
        })
      }
      /** *********************debug cao**********************/
      // 初始化线条容器
      if (this.LineSource == null) {
        this.LineSource = new Vector({
          wrapX: false
        })
      }
      if (this.LineLayer == null) {
        this.LineLayer = new VectorLayer({
          minResolution: 0,
          maxResolution: _dPR * 2.4,
          source: this.LineSource,
          zIndex: 1000,
          renderBuffer: 100,
          updateWhileAnimating: true,
          updateWhileInteracting: true,
          style: function(feature, resolution) {
            return TagStyle(feature, resolution)
          }
        })
      }
      /** *********************debug cao**********************/

      _iMap.addLayer(this.TagLayer)

      _iMap.addLayer(this.LineLayer)
    },

    // 释放地图中的资源
    releaseSource: function() {
      if (this.TagSource != null) {
        const self = this
        self.TagSource.forEachFeature(function(feature) {
          self.TagSource.removeFeature(feature)
        })
      }
    },

    releaseLineSource: function() {
      if (this.LineSource != null) {
        const self = this
        self.LineSource.forEachFeature(function(feature) {
          self.LineSource.removeFeature(feature)
        })
      }
    },

    /**
       * 获取全部围栏
       */
    getAllFenceInfo() {
      getLayerFenceList(this.mapId).then(res => {
        const RES = this.responseUse(res)
        this.tableFence = RES
        for (let i = 0; i < this.tableFence.length; i++) {
          switch (this.tableFence[i].fenceType) {
            case 'layer':
              this.tableFence[i].fenceType = this.$t('realtime.fenceFilterType.mainFence')
              break
            case 'alarm':
              this.tableFence[i].fenceType = this.$t('realtime.fenceFilterType.alarm')
              break
            case 'workspace':
              this.tableFence[i].fenceType = this.$t('realtime.fenceFilterType.workArea')
              break
            case 'camera':
              this.tableFence[i].fenceType = this.$t('realtime.fenceFilterType.monitor')
              break
            case 'check':
              this.tableFence[i].fenceType = this.$t('realtime.fenceFilterType.attendance')
              break
            case 'warehouse':
              this.tableFence[i].fenceType = this.$t('realtime.fenceFilterType.warehouse')
              break
            case 'operation':
              this.tableFence[i].fenceType = this.$t('realtime.fenceFilterType.operatingArea')
              break
            case 'polling':
              this.tableFence[i].fenceType = this.$t('realtime.fenceFilterType.inspection')
              break
            default:
              this.tableFence[i].fenceType = this.$t('realtime.fenceFilterType.unknownType')
              break
          }
        }
        this.fenceFilterType = this.resourceFilter(this.tableFence, 'fenceType')
      })
    },

    /**
       * 获取摄像头列表
       */
    getAllCameraInfo() {
      this.$api.realtimeposition.getLayerCameraList(this.mapId).then(res => {
        const RES = this.responseUse(res)
        this.tableCamera = RES
      })
    },

    // 初始化函数
    init() {
      const self = this
      // 加载地图树
      getMapTree().then((res) => {
        const RES = this.responseUse(res)
        if (typeof RES !== 'undefined') {
          this.mapTreeData = RES
        }
      })

      // 获取资源列表
      getAllDeptDetail().then(res => {
        const RES = this.responseUse(res)
        if (typeof RES !== 'undefined') {
          this.deptObjData = RES
          this.deptObjDataCopy = RES
        }
      })

      // 初始化地图控件
      self.initMap()
      releaseFence()
      // 获取全部摄像头信息
      // this.getAllCameraInfo();

      // 十秒钟去除一次老化数据
      self.myInterval1 = setInterval(function() {
        self.bAgeLock = true
        // 判断是不是已经没有位置数据了，通过时间差来判断

        if (self.lastUpdateTime != null) {
          const currentTime = new Date()
          const res = currentTime.getTime() - self.lastUpdateTime.getTime()// 相差的毫秒数
          if (res > 1000 * 5) {
            self.releaseSource()
          }
        }

        // 统计图层中现有的各种类型标签数量
        if (self.TagSource != null) {
          // 清零
          self.statisticInfo.staff = 0
          self.statisticInfo.celler = 0
          self.statisticInfo.car = 0
          self.statisticInfo.material = 0
          self.statisticInfo.machine = 0
          self.statisticInfo.boat = 0
          self.statisticInfo.unknow = 0
          // 清空资源列表
          self.tableResource = []

          const tempArr = self.TagSource.getFeatures()
          let type = ''
          for (let i = 0; i < tempArr.length; i++) {
            type = tempArr[i].get('type')
            // console.log("type: ", type);
            switch (type) {
              case 'staff' :
                self.statisticInfo.staff++
                break
              case 'visitor' :
                self.statisticInfo.celler++
                break
              case 'car' :
                self.statisticInfo.car++
                break
              case 'material' :
                self.statisticInfo.material++
                break
              case 'machine' :
                self.statisticInfo.machine++
                break
              case 'boat' :
                self.statisticInfo.boat++
                break
              case '' :
                self.statisticInfo.unknow++
                break
              default:
                break
            }

            // 收集资源信息
            const obj = {
              'name': tempArr[i].get('name'),
              'type': tempArr[i].get('type'),
              'resourceId': tempArr[i].get('resourceId'),
              'rateHeart': tempArr[i].get('rateHeart'),
              'showContrail': tempArr[i].get('showContrail')
            }

            switch (obj.type) {
              case 'staff':
                obj.type = self.$t('realtime.staff')
                break
              case 'car':
                obj.type = self.$t('realtime.car')
                break
              case 'visitor':
                obj.type = self.$t('realtime.celler')
                break
              case 'material':
                obj.type = self.$t('realtime.material')
                break
              case 'machine':
                obj.type = self.$t('realtime.machine')
                break
              case 'boat':
                obj.type = self.$t('realtime.machine')
                break
              default:
                obj.type = self.$t('realtime.unknow')
                break
            }
            self.tableResource.push(obj)

            // console.log("showContrail：", tempArr[i].get("showContrail"), "name：", tempArr[i].get("name"), "type：", tempArr[i].get("type"), "resourceId：", tempArr[i].get("resourceId"), "rateHeart：", tempArr[i].get('rateHeart'));
          }
          self.tableResource.sort(function(a, b) {
            if (a.name > b.name) {
              return -1
            }
            if (a.name < b.name) {
              return 1
            }
            return 0
          })

          self.resourceFilterType = self.resourceFilter(self.tableResource, 'type')

          self.updateHistogram()
        }
      }, 5000)

      // 初始化webSocket
      this.initPositionWebSocket()

      // 页面刚加载的时候更新柱状图数据
      this.updateHistogram()
    },

    // 更新柱状图
    updateHistogram() {
      // 根据数据中的最大值来动态调整柱状图的高度
      let staff_H = 3; let celler_H = 3; let car_H = 3; let material_H = 3; let machine_H = 3; let boat_H = 3; let unknow_H = 3; let max_H = 0

      for (const item in this.statisticInfo) {
        if (this.statisticInfo[item] > max_H) {
          max_H = this.statisticInfo[item]
        }
      }

      if (max_H > 0) {
        // 计算最大值与100的比值，并根据比值将所有数据进行缩放，从而实现定比值的动态高度
        const mult = max_H / 50
        staff_H = Math.round(this.statisticInfo.staff / mult <= 3 ? 3 : this.statisticInfo.staff / mult)
        celler_H = Math.round(this.statisticInfo.celler / mult <= 3 ? 3 : this.statisticInfo.celler / mult)
        car_H = Math.round(this.statisticInfo.car / mult <= 3 ? 3 : this.statisticInfo.car / mult)
        material_H = Math.round(this.statisticInfo.material / mult <= 3 ? 3 : this.statisticInfo.material / mult)
        machine_H = Math.round(this.statisticInfo.machine / mult <= 3 ? 3 : this.statisticInfo.machine / mult)
        boat_H = Math.round(this.statisticInfo.boat / mult <= 3 ? 3 : this.statisticInfo.boat / mult)
        unknow_H = Math.round(this.statisticInfo.unknow / mult <= 3 ? 3 : this.statisticInfo.unknow / mult)
      }

      // 统一更新统计柱状图
      $('.pillardiv_staff').height(staff_H)
      $('.pillardiv_celler').height(celler_H)
      $('.pillardiv_car').height(car_H)
      $('.pillardiv_material').height(material_H)
      $('.pillardiv_machine').height(machine_H)
      $('.pillardiv_boat').height(boat_H)
      $('.pillardiv_unknow').height(unknow_H)
    },

    // 刷新窗口
    windowRefresh: function() {
      this.mapHeight = window.innerHeight - 80 + 'px'
      this.mapWidth = window.innerWidth + 'px'
    },

    clearHeartBeatIntervalState() {
      if (this.waitTimeInterval != null) {
        window.clearInterval(this.waitTimeInterval)
        this.waitTimeInterval = null
        this.waitTime = 0
      }

      if (this.heartBeatInterval != null) {
        window.clearInterval(this.heartBeatInterval)
        this.heartBeatInterval = null
        this.order = 0
      }
    },

    sendHeartBeatInfo() {
      this.order++
      this.webSocketOnSend('HeartBeat:{order:' + this.order + ',timeStamp:' + (new Date().getTime()) + '}')
      this.waitTimeLock = true
      this.waitTime = 0
    },

    /**
       * 初始化位置websocket
       */
    initPositionWebSocket() {
      // 初始化websocket
      this.websock = new WebSocket(webSockUrl)
      this.websock.onopen = this.webSocketOnOpen
      this.websock.onmessage = this.webSocketOnMessage

      // this.websock.websock = this.webSocketReconnection;
      this.websock.onclose = this.webSocketOnClose
      this.websock.onerror = this.webSocketOnError
    },

    /**
       * 注册
       */
    webSocketOnOpen() {
      const self = this
      console.log('webSocket连接成功')
      if (this.websock.readyState === 1) {
        // 发送时间戳
        this.systomID = (new Date().getTime()).toString()
        let param = JSON.stringify({ register: this.systomID })
        this.webSocketOnSend(param)

        param = JSON.stringify({ key: this.systomID, layerId: this.mapId })
        this.webSocketOnSend(param)

        if (self.heartBeatInterval == null) {
          self.sendHeartBeatInfo()
          self.heartBeatInterval = setInterval(() => {
            self.sendHeartBeatInfo()
          }, 20 * 1000)
        }

        if (self.waitTimeInterval == null) {
          self.waitTimeInterval = setInterval(() => {
            if (self.waitTimeLock) {
              self.waitTime++
              // 大于10秒，就认为是断开了连接
              if (self.waitTime > 10) {
                self.waitTime = 0
                self.order = 0
                self.waitTimeLock = false
                self.webSocketOnOpen()
              }
            }
          }, 1000)
        }
      }
    },
    /**
       * 连接建立失败后进行重连
       */
    webSocketReconnection() {
      this.initPositionWebSocket()
    },

    /**
       * 数据发送
       */
    webSocketOnSend(data) {
      this.websock.send(data)
    },
    /**
       * 断开连接
       */
    webSocketOnClose(e) {
      console.log('断开连接', e)
      if (this.$route.path === '/RealTimePosition_Tunnel') {
        setTimeout(() => {
          console.log('位置数据webSocket重连')
          this.initPositionWebSocket()
        }, 10000)
      }
    },

    webSocketOnError(e) {
      console.log('连接错误', e)
      if (this.$route.path === '/RealTimePosition_Tunnel') {
        setTimeout(() => {
          console.log('位置数据webSocket重连')
          this.initPositionWebSocket()
        }, 10000)
      }
    },

    /**
       * 数据接收
       */
    webSocketOnMessage(e) {
      const self = this
      if (e === undefined) {
        console.log('返回值为undefined')
      } else if (undefined != e.data) {
        const jsonData = JSON.parse(e.data)
        if (jsonData.message === 'handshake') {
          console.log('注册成功')
        } else if (jsonData.message == 'HeartBeat') {
          self.waitTime = 0
          self.waitTimeLock = false
        } else if (jsonData.message === 'gateEvent') {
          for (let i = 0; i < jsonData.data.length; i++) {
            if (this.gateEventTableData.length > 4) {
              this.gateEventTableData.pop()
            }
            this.gateEventTableData.unshift(jsonData.data[i])
          }
        } else if (jsonData.message === 'Point') {
          // console.log(jsonData);
          this.lastUpdateTime = new Date()
          if (self.bLockEx) {
            self.bLockEx = false // 锁住，防止这次没有执行完，下次的数据就已经到了
            const format = new GeoJSON()
            const newFeatures = format.readFeatures(jsonData.data) // 使用ol自带的函数，解析GeoJson数据
            // 遍历元素数据
            newFeatures.forEach(function(f) {
              if (self.mapId.toString() === (f.get('idx')).toString()) {
                const tempcoord = f.getGeometry().getCoordinates()
                const ncoords = _TransPixel(tempcoord)

                // 直接在地图的source中通过ID查询，直接获取得到标签在地图中的信息
                const tag = self.TagSource.getFeatureById(f.get('resourceId'))
                if (tag != null) {
                  // 说明之前已经添加过，只需更新位置信息
                  // 先对比坐标移动是不是在半米以内，在半米以内则不跟新
                  if (tag.get('pos_x') - 0.3 > f.get('pos_x') || tag.get('pos_x') + 0.3 < f.get('pos_x') ||
                      tag.get('pos_y') - 0.3 > f.get('pos_y') || tag.get('pos_y') + 0.3 < f.get('pos_y')) {
                    // 坐标超过半米

                    // 根据是否显示轨迹的状态值来判断当前标签是否显示路径
                    /** ************************debug cao***************************/
                    if (tag.get('showContrail')) {
                      const from_to = [_TransPixel([tag.get('pos_x'), tag.get('pos_y')]), ncoords]
                      // console.log('线两点的数据：', from_to);
                      const lineFeature = new Feature(new LineString(from_to))
                      self.setLineStyle(tag.get('contrailColor'))
                      lineFeature.setStyle(self.styles.linestring)
                      self.LineSource.addFeature(lineFeature)
                    }

                    /** ************************debug cao***************************/

                    // 更新坐标
                    tag.set('pos_x', f.get('pos_x'))
                    tag.set('pos_y', f.get('pos_y'))
                    tag.set('axis', f.get('axis'))
                    tag.getGeometry().setCoordinates(ncoords)
                    // 如果打开了气泡，同步更新气泡坐标
                    updateOverlayPosition(f.get('resourceId'), ncoords)
                  }

                  // 搜索资源
                  if (self.searchLock) {
                    if (self.searchValue === tag.get('resourceId')) {
                      const coord1 = tag.getGeometry().getCoordinates()
                      _Popup(tag, coord1)
                      setMapCenter(coord1)
                      self.searchLock = false // 搜索到了，再关闭锁
                    }
                  }
                } else {
                  // 之前没有添加过，直接添加
                  f.getGeometry().setCoordinates(ncoords)
                  // 为新添加的元素设置ID
                  f.setId(f.get('resourceId'))
                  f.set('showContrail', false) // 设置轨迹是否显示
                  f.set('contrailColor', self.randomRGB())
                  self.TagSource.addFeature(f)
                }
              }
            })

            if (self.bAgeLock) {
              const tempArr = self.TagSource.getFeatures().slice(0)

              newFeatures.forEach(function(f) {
                if (f.get('resourceId') != undefined) {
                  let len = tempArr.length
                  while (len > 0) {
                    len--
                    if (tempArr[len].get('resourceId') === f.get('resourceId')) {
                      tempArr.splice(len, 1)
                    }
                  }
                }
              })
              const len = tempArr.length

              for (let i = 0; i < len; i++) {
                const tag = self.TagSource.getFeatureById(tempArr[i].get('resourceId'))
                if (tag != null) {
                  self.TagSource.removeFeature(tag)
                }
              }
              self.bAgeLock = false
            }
            self.bLockEx = true
          }
        }
      }
    },
    setLineStyle(rgb) {
      this.styles = {
        'linestring': new Style({
          stroke: new Stroke({
            color: rgb,
            width: 1
          }),
          zIndex: 999
        })
      }
    },
    // 查找SOS告警对象
    checkSOSInfo(info) {
      if (parseInt(this.mapId) === info.layerId && this.TagSource) {
        const tag = this.TagSource.getFeatureById(info.resourceId)
        if (tag) {
          flashAnimate(tag)
        }
      }
    }
  }
}
</script>

<style>

  #mapbox2 .ol-unselectable {
    bottom: 30px !important;
  }

  .layer_detail_dialog {
    width: 600px !important;
    margin-top: 25vh !important;
  }

  .el-select-dropdown {
    z-index: 22222 !important;
  }

  .collapse1 .el-collapse-item__header {
    color: #fff;
    font-size: 12px;
    font-weight: 400;
    /* background-color: linear-gradient(180deg, #1f59ad, #3488de) !important; */
    background-image: linear-gradient(180deg, #1f59ad, #3488de) !important;
    height: 30px;
    padding-left: 100px;
    text-align: center;
  }

  /* .collapse1 .el-collapse-item {
    border-radius: 10px;
  } */

  .collapse2 .el-collapse-item__header {
    color: #000;
    font-size: 12px;
    font-weight: 400;
    background-image: linear-gradient(180deg, #fff, #fff) !important;
    padding-left: 20px;
    /* border-radius: 0px; */
    /* background-color: #fff; */
  }

  /* .has-gutter .is-leaf {
    background-color: #fff;
    color: #000;
  } */

  /****************debug cao****************/
  /*视频窗口样式*/

  /*气泡样式*/
  .ol-popup {
    position: absolute;
    background-color: white;
    -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
    filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
    padding: 5px;
    border-radius: 5px;
    border: 1px solid #cccccc;
    bottom: 15px;
    left: -50px;
    /*min-width: 150px;*/
    white-space: nowrap;
  }

  /* .ol-popup li {
    list-style-type: none;
    font-size: 12px;
  }*/

  /* #popup-content li{
    list-style-type: none;
    font-size: 12px;
  } */

  #popup-content {
    padding: 10px;
  }

  .ol-popup:after,
  .ol-popup:before {
    top: 100%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
  }

  .ol-popup:after {
    border-top-color: white;
    border-width: 10px;
    left: 55px;
    margin-left: -10px;
  }

  .ol-popup:before {
    border-top-color: #cccccc;
    border-width: 10px;
    left: 55px;
    margin-left: -10px;
  }

  .ol-popup-closer {
    text-decoration: none;
    position: absolute;
    top: 2px;
    right: 8px;
  }

  .ol-popup-closer:after {
    content: "✖";
  }

  /****************debug cao****************/

  .card-monitor .el-card__body {
    padding: 0;
  }
</style>

<style scoped>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    /* font-size: 14px !important; */
    padding-right: 8px;
  }

  .el-tree-node__label {
    max-width: 165px;
  }

  .gateeventtable {
    position: absolute;
    width: 520px;
    top: 10px;
    left: 50%;
    margin-left: -260px;

  }

  #body {
    width: 100%;
    height: 100%;
    overflow: hidden;
    background-color: #fff;
  }

  .handle-box {
    background-color: #fff;
    padding-top: 5px;
    padding-left: 10px;
    padding-right: 10px;
    padding-bottom: 5px;
    /* text-align: right; */
    /*margin-top: 10px;*/

    /*margin-bottom: 15px;*/
  }

  #mapbox2 {
    background-color: #fff;
    z-index: 10000;
  }

  /*地图树显示模块*/
  .showhidediv {
    position: absolute;
    left: 10px;
    margin-top: 40px;
    width: 200px;
    float: right;
    z-index: 1000;
  }

  /*发送告警时的区域列表*/
  .send-alart-div {
    position: absolute;
    border: rgb(137, 240, 77) 1px solid;
    background-color: #fff;
    width: 300px;
    height: 340px;
    right: 10px;
    top: 80px;
    z-index: 100;
    padding: 20px;
  }

  /*一键撤离表格下方按钮*/
  .customdiv {
    text-align: center;
    padding-top: 9px;
  }

  /* 本层统计信息 */
  .show5 {
    position: absolute;
    left: 200px;
    bottom: 21px;
    padding-left: 10px;
  }

  .show5 .show_subdiv {
    /* float: left; */
    /* margin-left: 15px; */
    width: 50px;
    position: absolute;
    bottom: 0px;
  }

  .show5 .show_subdiv span {
    display: block;
    width: 50px;
    line-height: 30px;
    text-align: center;
  }

  .show5 .show_subdiv div {
    margin: 0 auto;
    width: 30px;
    background-color: #f1a11e;
  }

  /* 资源列表中摄像头预览功能 */
  /* .camera-preview {
    position: absolute;
    right: 0px;
    bottom: 0px;
  } */

  .colCardBox {
    position: absolute;
    top: 22px;
    right: 236px;
    z-index: 11112;
  }

  /* 右边卡片相关 */
  .card-box {
    position: absolute;
    width: 300px;
    right: 0px;
    z-index: 2043;
  }

  .handle-div1 {
    width: 210px;
    margin-left: 50px;
    text-align: right;
  }

  .handle-div2 {
    width: 100%;
    margin-top: 10px;
    text-align: center;
  }

  .handle-div3 {
    width: 100%;
    margin-top: 10px;
    border: 1px solid #409eff;
    border-radius: 5px;
  }

  .handle-div3 .title-div3 {
    width: 100%;
    height: 30px;
    background-color: #409eff;
    text-align: center;
  }

  .handle-div3 .title-div3 span {
    font-size: 14px;
    font-weight: 600;
    line-height: 30px;
  }

  .handle-div3 .filter-tree {
    width: 100%;
  }

  .handle-div4 {
    margin-top: 10px;
  }

  .span_num {
    color: #000;
    font-size: 20px;
  }

  /* 摄像头跟踪视频窗口 */
  .card-monitor {
    position: absolute;
    z-index: 111111;
  }

</style>
